<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      th:replace="~{common/base :: Layout(~{::content},~{::title}, _,_,_,~{::ruleMenu},_,_,_,~{::scripts},_)}">

<title>规则列表</title>
<content>
    <div class="layui-tab-brief layui-tab">
        <ul class="layui-tab-title site-demo-title">
            <li class="layui-this"><a><cite>规则列表</cite></a></li>
        </ul>
    </div>
    <div class="layui-fluid" style="padding: 15px;">
        <div class="layui-row layui-col-space15">
            <div class="layui-col-md12">
                <div class="layui-card">
                    <!--                    <div class="layui-card-header ">-->
                    <!--                        <h1>规则列表</h1>-->
                    <!--                    </div>-->

                    <div class="layui-card-body">
                        <table class="layui-hide" id="ruleTable" lay-filter="buttons"></table>
                    </div>
                </div>
            </div>
        </div>
    </div>

</content>


<dd class="layui-this" th:fragment="ruleMenu">
    <a href="/pages/rules">规则列表</a>
</dd>

<div th:fragment="scripts">

    <script th:inline="none" type="text/html" id="barDemo">
<!--        <button class="layui-btn layui-btn-xs" lay-event="detail">查看</button>-->
        <button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</button>
    </script>

    <script type="text/html" id="layerRefresh">
        <div class="layui-btn-container">
            <button id="createButton"
                    class="layui-btn layui-btn-normal layui-btn-radius"
                    lay-event="createRule">
                创建规则
            </button>
            <button id="refreshButton"
                    class="layui-btn layui-btn-checked layui-btn-radius"
                    lay-event="refresh">
                刷新
            </button>
        </div>
    </script>

    <script th:inline="none">
        layui.use(['form', 'table'], function () {
            var table = layui.table;
            var form = layui.form;

            var $ = layui.jquery, layer = layui.layer; //独立版的layer无需执行这一句
            //第一个实例
            table.render({
                elem: '#ruleTable',
                url: '/api/rules/', //数据接口
                page: true,  //开启分页
                toolbar: '#layerRefresh',
                defaultToolbar:['exports', 'print'],
                //width: 1200,
                cols: [
                    [ //表头
                        // {type: 'checkbox'},
                        {field: 'ruleName', title: '规则名称', sort: true, align: 'center'},
                        {field: 'ruleToDevice', title: '对应设备', align: 'center'}, //, templet:ruletodev
                        {field: 'ruleToFunction', title: '规则设定', align: 'center', templet:setting},
                        {field: 'ruleExecute', title: '执行功能', align: 'center', templet:exeSet},
                        // {field: 'ruleDescribe', title: '规则描述', align: 'center'},
                        // {field: 'ruleCreateTime', title: '创建时间', sort: true, align: 'center'},
                        // {field: 'ruleStatus', title: '规则状态', sort: true, align: 'center'},
                        {field:'ruleStatus',
                            title:'规则状态',
                            align:'center',
                            templet:statusTpl},
                        {title: '操作', align: 'center',toolbar: '#barDemo'
                        }
                    ]
                ]
            });

            //表内开关
            layui.use(['form'], function() {
                var form = layui.form
                    , layer = layui.layer;

                var interval = 3000;
                var changeRuleAlert = function() {
                    $.ajax({
                        type: "get",
                        url: "/api/alertDetails",
                        async: false,//同步提交。不设置则默认异步，异步的话，最后执行ajax
                        // data: JSON.stringify({'ruleId': data.elem.attributes['switch_rule_id'].nodeValue}),
                        contentType: "application/json",
                        success: function (data) {
                            var type = Object.keys(data);
                            var alt;
                            // [Status,Execute,ruleJudge,Threshold,Temperature] = data[type];
                            Status = data["ruleCurrentStatus"];
                            // System.out.println("type[0]:"+type[0]);
                            Execute = data["ruleExecuteStatus"];
                            ruleJudge = data["ruleJudge"];
                            Threshold = data["ruleThreshold"];
                            ident = data["ident"];
                            alertDeviceName = data["alertDeviceName"]
                            if(ident == 1){Temperature = data["Humidity"];}
                            if(ident == 0){Temperature = data["TemperatureDeg"];}
                            // Temperature = data[type[4]];
                            if(Status == 1 & Execute == 1){
                                switch (ruleJudge) {
                                    case 0:
                                        if (Temperature = Threshold) {
                                            alt = alert(alertDeviceName);
                                            if(alt = 1){clearInterval(updateAlert);}
                                        };
                                        break;
                                    case 1:
                                        if (Temperature < Threshold) {
                                            alt = alert(alertDeviceName);
                                            if(alt = 1){clearInterval(updateAlert);}
                                        };
                                        break;
                                    case 2:
                                        if (Temperature > Threshold) {
                                            alt = alert(alertDeviceName);
                                            if(alt = 1){clearInterval(updateAlert);}
                                        };
                                        break;
                                }
                                // if (Temperature > Threshold) {
                                //     alt = alert();
                                //     if(alt = 1){clearInterval(updateAlert);}
                                // }
                            }
                            return alt;
                            //console.log(data);
                            //console.log(sessionStorage.getItem("productNames"));
                        },
                    });
                };
                var updateAlert = setInterval(changeRuleAlert,interval);

                //监听指定开关
                form.on('switch(changeRuleStatus)', function changeRuleStatus(data) {
                    $.ajax({
                        type: "put",
                        url: "/api/changeRuleStatus",
                        async: false,//同步提交。不设置则默认异步，异步的话，最后执行ajax
                        data: JSON.stringify({'ruleId': data.elem.attributes['switch_rule_id'].nodeValue}),
                        contentType: "application/json",
                        success: function (ev) {
                            console.log(ev.data);
                            clearInterval(updateAlert);
                            updateAlert = setInterval(changeRuleAlert,interval);
                        },
                        error: function (ev) {
                            console.log("开关失败" + ev.responseText);
                        }
                    });
                });
            });


                 //监听告警
                // form.on('switch(changeRuleStatus)', function changeRuleAlert(data){
                //     $.ajax({
                //         type: "get",
                //         url: "/api/alertDetails",
                //         async: false,//同步提交。不设置则默认异步，异步的话，最后执行ajax
                //         data: JSON.stringify({'ruleId': data.elem.attributes['switch_rule_id'].nodeValue}),
                //         contentType: "application/json",
                //         success: function (ev) {
                //             console.log(ev.data);
                //         },
                //     });
                // });



            // 头工具栏事件
            table.on('toolbar(buttons)', function (obj) {

                var checkStatus = table.checkStatus('test');
                switch (obj.event) {
                    case 'createRule':
                        notice();
                        break;
                    case 'refresh':
                        table.reload("ruleTable")
                        break;
                }
                ;
            });


            //监听工具条
            table.on('tool(buttons)', function (obj) {

                var data = obj.data;
                if (obj.event === 'detail') {
                    // layer.('ID：' + data.ruleId + ' 的查看操作');
                    location.href = "/pages/ruleDetails?ruleId=" + data.ruleId;
                } else if (obj.event === 'del') {
                    layer.confirm('确定删除吗', function (index) {
                        $.ajax({
                            type: "delete",
                            url: "/api/rule",
                            async: false,//同步提交。不设置则默认异步，异步的话，最后执行ajax
                            data: JSON.stringify({'ruleId': data.ruleId}),
                            contentType: "application/json",
                            // processData: false,
                            // cache: false,
                            success: function (ev) {
                                if (ev.data == "删除成功") {
                                    obj.del();
                                    layer.msg(ev.data);
                                    layer.close(index);
                                    table.reload("ruleTable");
                                } else {
                                    layer.msg(ev.data);
                                    layer.close(index);
                                }
                            }
                        });
                    });
                }
            });

            function getselect() {
                $.ajax({
                    type: "get",
                    url: "/api/ruleToDevices",
                    async: false,//同步提交。不设置则默认异步，异步的话，最后执行ajax
                    contentType: "application/json",
                    success: function (data) {
                        sessionStorage.setItem("deviceNames", JSON.stringify(data));
                        //console.log(data);
                        //console.log(sessionStorage.getItem("productNames"));
                    },
                    error:function(data){
                        console.log("获取设备失败"+data.responseText);
                        layer.msg("获取设备识别失败");
                    }
                });
                layui.use('form', function(){  //此段代码必不可少
                    var form = layui.form;
                    form.render("select");
                });
            }

            function getselect2() {
                $.ajax({
                    type: "get",
                    url: "/api/ruleParas",
                    async: false,//同步提交。不设置则默认异步，异步的话，最后执行ajax
                    contentType: "application/json",
                    success: function (data) {
                        sessionStorage.setItem("functionNames", JSON.stringify(data));
                        //console.log(data);
                        //console.log(sessionStorage.getItem("productNames"));
                    },
                    error:function(data){
                        console.log("获取功能失败"+data.responseText);
                        layer.msg("获取功能识别失败");
                    }
                });
            }

            //触发告警信息
            function alert(alertDeviceName) {
                //示范一个公告层
                layer.open({
                    type: 2
                    ,
                    title: "告警信息"
                    ,
                    closeBtn: 1
                    ,
                    area: ['300px', '200px']
                    ,
                    shade: 0.3
                    ,
                    id: 'LAY_layuipro1' //设定一个id，防止重复弹出
                    ,
                    btn: ['确定']
                    ,
                    btnAlign: 'c'
                    ,
                    moveType: 1 //拖拽模式，0或者1
                    ,
                    content: '/pages/ruleAlert'
                    ,
                    success:function(){
                        sessionStorage.setItem("alertDeviceName", alertDeviceName);

                        return 1;
                    },
                    // success: function (layero) {
                    //     var btn = layero.find('.layui-layer-btn');
                    //     btn.find('.layui-layer-btn0').attr({
                    //         href: 'http://www.layui.com/'
                    //         , target: '_blank'
                    //     });
                    // }
                });
            }

            //触发创建规则弹出层
            function notice(){
                //示范一个公告层
                layer.open({
                    type: 2
                    ,
                    title: "创建规则"
                    ,
                    closeBtn: 1
                    ,
                    area: ['600px', '600px']
                    ,
                    shade: 0.3
                    ,
                    id: 'LAY_layuipro' //设定一个id，防止重复弹出
                    ,
                    btn: ['提交', '重置', '取消']
                    ,
                    btnAlign: 'c'
                    ,
                    moveType: 1 //拖拽模式，0或者1
                    ,
                    content: '/pages/ruleCreate'
                    ,

                    // success: function (layero) {
                    //     var btn = layero.find('.layui-layer-btn');
                    //     btn.find('.layui-layer-btn0').attr({
                    //         href: 'http://www.layui.com/'
                    //         , target: '_blank'
                    //     });
                    // }
                    success:function(){
                        getselect();
                        getselect2();
                    },
                    yes: function (index, layero) {

                        // 获取弹出层中的form表单元素
                        var formSubmit = layer.getChildFrame('form', index);
                        // // 获取表单中的提交按钮（在我的表单里第一个button按钮就是提交按钮，使用find方法寻找即可）
                        var submited = formSubmit.find('button')[0];
                        // // 触发点击事件，会对表单进行验证，验证成功则提交表单，失败则返回错误信息
                        submited.click();
                        // layer.close(index);
                        // 弹出层关闭的操作在子层的js代码中完成

                    },
                    btn2: function (index, layero) {
                        //按钮【重置】的回调
                        // 获取弹出层中的form表单元素
                        var formSubmit = layer.getChildFrame('form', index);
                        // // 获取表单中的提交按钮（在我的表单里第一个button按钮就是提交按钮，使用find方法寻找即可）
                        var submited = formSubmit.find('button')[1];
                        submited.click();
                        return false;
                    }
                });
                layui.use('form', function(){  //此段代码必不可少
                    var form = layui.form;
                    form.render("select");
                });
            };
        });

        var statusTpl = function (d) { // 参数d是当前行数据
            var ruid = d.ruleId;
            var str = '<input type="checkbox" lay-filter="changeRuleStatus" lay-skin="switch" lay-text="启用|禁用" ';
            if(d.ruleStatus == 1){
                str = str + 'checked switch_rule_id='+ruid+'> ';
            }else{
                str = str + 'switch_rule_id='+ruid+'> ';
            }
            return str;
        };

        var setting = function (d) {
            var rulePara = d.rulePara;
            var para=['=','<','>'];
            var ruleJudge = para[d.ruleJudge];
            var ruleParaThreshold = d.ruleParaThreshold;
            var strg = rulePara + ruleJudge + ruleParaThreshold;
            return strg;
        }

        var exeSet = function (d) {
            if(d.ruleExecute==1){
                var exestr = '警告日志';}
            if(d.ruleExecute==0){
                exestr = '关闭设备';}
            return exestr;
        }
        // var ruletodev = function (d) {
        //     var devstr = d.ruleToDevice;
        //     return devstr;
        // }
    </script>

</div>
</html>

